import { cancelOrder, queryOrder,getShopStatus } from '@src/api/catering'
import payBehavior from '../order/payBehavior'
import dayjs from 'dayjs'
import $math from '@src/common/math'
import router from '@src/router'
import { get } from '@src/common/wxCache'



Component({
  behaviors: [payBehavior],
  data: {
    order: null,
    giftList: [],
    sumNum:0,
    pageFrom:'',
    isOpenTime:true,
    deliveryInfo:{}
  },
  methods: {
    onLoad(options) {
      let orderNo = options.orderNo
      if(options.pageFrom){
        this.setData({ pageFrom: options.pageFrom })
      }
      this.setData({ orderNo: orderNo })
    },
    onLogin() {
      this.fetchData()
    },
    onPullDownRefresh() {
      this.fetchData()
      wx.stopPullDownRefresh()
    },
    fetchData() {
      let data = { orderNo: this.data.orderNo }
      queryOrder(data).then((res) => {
        if (res.code === 0) {
          let {items,giftSnapshots,deliveryInfo} = res.data
          // this.setData({
          //   order: res.data,
          //   giftList:res.data.giftSnapshots,
          //   shopInfo: res.data.shopInfo,
          // })
          if(giftSnapshots&&giftSnapshots.length>0){
            for (var i = giftSnapshots.length - 1; i >= 0; i--) {
              var targetNode = giftSnapshots[i]
              for (var j = 0; j < i; j++) {
                if (targetNode.productId == giftSnapshots[j].productId) {
                  giftSnapshots[j].num+=targetNode.num
                  giftSnapshots.splice(i, 1)
                  break
                }
              }
            }
          }
          let sumNum = 0
          if(items.length>0){
            items.forEach(element => {
              sumNum+=$math.mul(element.fee, 100, 0)
            });
          }
          this.setData({sumNum,order: res.data,deliveryInfo,
            shopInfo: res.data.shopInfo,giftList:giftSnapshots})
          this.payTimeCountDown()
          let {orderStatus} = res.data
          let {pageFrom} = this.data
          this.setShopStatus()

          
        }
      })
    },
    payTimeCountDown() {
      // 支付倒计时
      let createTime = dayjs(this.data.order.createTime, 'YYYY-MM-DD HH:mm')
      let endTime = createTime.unix() + 30 * 60
      let remainTime = endTime - dayjs().unix()
      this.setData({ remainTime: remainTime, endTime })
      let orderStatus = this.data.order.orderStatus
      if (remainTime >= 0 && (orderStatus === 2 || orderStatus === 1)) {
        this.cutTime(remainTime)
      }
    },
    // 倒计时
    cutTime(remainTime) {
      let minute = Math.floor(remainTime / 60)
      let second = remainTime % 60
      if (this.data.timer) {
        clearInterval(this.data.timer)
      }
      let timer = setInterval(() => {
        let remainTime = this.data.endTime - dayjs().unix()
        if (remainTime <= 0 && this.data.timer) {
          clearInterval(this.data.timer)
          this.setData({ timer: null, remainTime: 0 })
          this.fetchData()
          return
        }
        let minute = Math.floor(remainTime / 60)
        let second = remainTime % 60
        this.setData({
          remainTime: remainTime,
          remainTimeM: minute,
          remainTimeS: second,
        })
      }, 1000)
      this.setData({
        remainTime: remainTime,
        remainTimeM: minute,
        remainTimeS: second,
        timer: timer,
      })
    },
    handleToPay() {
      if(!this.setShopStatus()) return
      let payChannels = []
      if (this.data.shopInfo.payTypes.includes(3)) {
        payChannels.push('balance')
      }
      if (this.data.shopInfo.payTypes.includes(1)) {
        payChannels.push('wx')
      }
      let orderNo = this.data.order.orderNo
      let params = {
        orderNo: orderNo,
        payFee: $math.mul(this.data.order.payFee, 100, 0),
        hasDiscount: this.data.order.discountFee > 0,
        payChannels: payChannels,
      }
      this.toCateringPay(params)
        .then(() => {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 2000,
          })
          this.fetchData()
        })
        .catch((err) => {
          console.info('error', err)
        })
    },
    toTakeOrder() {
      router.redirectTo({ name: 'codeorder/index' })
    },
    handleCancelOrder() {
      let data = {
        orderNo: this.data.orderNo,
      }
      wx.showModal({
        title: '',
        content: '要取消订单吗？',
        cancelText: '点错了',
        confirmText: '是的',
        confirmColor: '#F56C6C',
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '订单取消中...' })
            cancelOrder(data)
              .then((res) => {
                wx.hideLoading()
                if (res.code === 0) {
                  wx.showToast({
                    title: '取消订单成功',
                    icon: 'success',
                    duration: 2000,
                  })
                }
                this.fetchData()
              })
              .catch(() => {
                wx.hideLoading()
              })
          }
        },
      })
    },
    isCancelTab(){
      console.log('清空号牌操作')
      let {dinnerTabNum} =getApp().globalData
      if(!dinnerTabNum) return
      if(dinnerTabNum){
        let countDown = 10
        var timeClose = setInterval(()=>{
          countDown--
          if(countDown == 0){
            getApp().globalData.dinnerTabNum = ''
            clearInterval(timeClose)
          }
        },1000)
      }
    },
    async setShopStatus(){
      let isOpenTime  = true
      let res = await getShopStatus({shopId:this.data.shopInfo.shopId})
      // .then(res=>{
        let {isOpen,status,disabled} = res.data
        isOpenTime= isOpen == true&&(status == 1||status==2)&&disabled==false?true:false
        this.setData({isOpenTime})
        return isOpenTime
      // })
    }
  },
})
